﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using System.Data;
using System.IO;

namespace KPIS.GERP.GIMS.APP.APP_UI.Edit_Form
{
    public partial class ICM_Purchase_Request_Bidder : System.Web.UI.Page
    {
        Common.Main cn = new Common.Main();
        CommandControl cmdFac = new CommandControl();
        IBLLDocument bllPprFile = new DocumentBLL();
        PurchaseRequestItemBLL bllPrItem = new PurchaseRequestItemBLL();
        BidderBLL bllBidder = new BidderBLL();
        IBLLSysVat bllSysVat = new SysVatBLL();
        SysControlBLL bllSysControl = new SysControlBLL();
        BidderQuotationBLL bllBidderQuo = new BidderQuotationBLL();
        IBLLSysDurationType bllDurationType = new SysDurationTypeBLL();
        IBLLMasterContact bllMasContact = new MasterContactBLL();
        private const int SellerPerRequest = 10;
        private const int ItemsPerRequest = 10;
        double totalPrice = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadVat();
                LoadDefaultVat();
                LoadDurationType();
                rdbDuration.Attributes.Add("onclick", "return ChangeDurationRequire('" + panelDuration.ClientID + "','" + panelDateReq.ClientID + "','" + panelDateReqPick.ClientID + "')");
                rdbDate.Attributes.Add("onclick", "return ChangeDateRequire('" + panelDuration.ClientID + "','" + panelDateReq.ClientID + "','" + panelDateReqPick.ClientID + "')");
                GetKeyValue();
            }

            if (rdbDate.Checked)
            {
                panelDuration.Attributes.Add("style", "visibility:hidden");
                panelDateReq.Attributes.Add("style", "visibility:visible");
                panelDateReqPick.Attributes.Add("style", "visibility:visible");
            }
            if (rdbDuration.Checked)
            {
                panelDuration.Attributes.Add("style", "visibility:visible");
                panelDateReq.Attributes.Add("style", "visibility:hidden");
                panelDateReqPick.Attributes.Add("style", "visibility:hidden");
            }
        }

        protected void RadTabStrip1_TabClick(object sender, RadTabStripEventArgs e)
        {
            if (RadTabStrip1.SelectedTab.Value == "Detail")
            {
                GetKeyValue();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Item")
            {
                LoadGridItem();
                lblVatTypeName.Text = lblVatType.Text;
            }
            else if (RadTabStrip1.SelectedTab.Value == "File")
            {
                LoadGridFile();
            }
        }

        #region Tab ข้อมูลหลักผู้ขาย

        private int GetSeq()
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            return seq;
        }

        private int GetPrSeq()
        {
            int seq = Convert.ToInt32(Request.QueryString["PrSeq"]);
            return seq;
        }

        protected void LoadVat()
        {
            IList<SysVatInfo> info = bllSysVat.GetSysVat();
            cbVatType.DataSource = info;
            cbVatType.DataBind();
        }

        protected void LoadDefaultVat()
        {
            SysControlInfo info = bllSysControl.GetDefaultData();
            hdDefaultVat.Value = info.VatPercent.ToString();
        }

        protected void LoadDurationType()
        {
            IList<SysDurationTypeInfo> infoList = bllDurationType.GetSysDurationType();
            cbDurationType.DataSource = infoList;
            cbDurationType.DataBind();
        }

        protected void GetKeyValue()
        {
            BidderInfo infoBidder = bllBidder.GetBidder(GetSeq());
            lblSeller.Text = infoBidder.InfoMasContact.Name_th.ToString();
            cbSeller.SelectedValue = infoBidder.InfoMasContact.Seq.ToString();
            cbSeller.Text = infoBidder.InfoMasContact.Name_th.ToString();
            cbVatType.SelectedValue = infoBidder.InfoVat.Seq.ToString();
            txtVatPercent.Text = infoBidder.VatPercent.ToString();
            txtDate.Text = ((DateTime)infoBidder.Date).ToString("dd/MM/yyyy");
            if (infoBidder.DueDay != null)
            {
                lblDuration.Text = "ภายใน " + infoBidder.DueDay + " " + infoBidder.InfoDurationType.Name;
            }
            else if (infoBidder.DueDate != null)
            {
                lblDuration.Text = "ภายในวันที่ " + ((DateTime)infoBidder.DueDate).ToString("dd/MM/yyyy"); ;
            }
            else
            {
                lblDuration.Text = "";
            }

            if (infoBidder.DueDay != null)
            {
                rdbDuration.Checked = true;
                rdbDate.Checked = false;
                txtDurationReq.Text = infoBidder.DueDay.ToString();
                cbDurationType.SelectedValue = infoBidder.InfoDurationType.Seq.ToString();
            }
            else if (infoBidder.DueDate != null)
            {
                rdbDate.Checked = true;
                rdbDuration.Checked = false;
                txtDateReq.Text = ((DateTime)infoBidder.DueDate).ToString("dd/MM/yyyy");
            }

            if (infoBidder.DueDate == null && infoBidder.DueDay == null)
            {
                rdbDuration.Checked = true;
            }

            cmdFac.ViewCommand(panelList_Detail, panelGrid_Detail, panelCommand_Detail);
            cmdFac.SetViewMode(panelDateReqPick);
            cmdFac.SetPanelList(panelDateReqPick, "View");
            cmdFac.SetViewMode(panelDateReq);
            cmdFac.SetPanelList(panelDateReq, "View");
            cmdFac.SetViewMode(panelDuration);
            cmdFac.SetPanelList(panelDuration, "View");
        }

        protected void cbSeller_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<MasterContactInfo> infoList = bllMasContact.GetMasterContactNoBlackList(e.Text);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + SellerPerRequest, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cbSeller.Items.Add(new RadComboBoxItem(infoList[i].Name_th, infoList[i].Seq.ToString() + ":" + infoList[i].InfoVat.Seq));
                TableRow tr = new TableRow();
                TableCell tdGroup = new TableCell();
                Label lblGroup = new Label();
                lblGroup.Text = infoList[i].InfoGroup.Name;
                tdGroup.Width = Unit.Pixel(200);
                tdGroup.Controls.Add(lblGroup);
                tr.Cells.Add(tdGroup);

                TableCell tdCode = new TableCell();
                Label lblCode = new Label();
                lblCode.Text = infoList[i].Gfmis_code;
                tdCode.Width = Unit.Pixel(150);
                tdCode.Controls.Add(lblCode);
                tr.Cells.Add(tdCode);

                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Name_th;
                tdName.Width = Unit.Pixel(150);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);

                TableCell tdAddress = new TableCell();
                Label lblAddress = new Label();
                lblAddress.Text = infoList[i].Address;
                tdAddress.Width = Unit.Pixel(190);
                tdAddress.Controls.Add(lblAddress);
                tr.Cells.Add(tdAddress);
                ((Table)cbSeller.Items[j].FindControl("tableSeller")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }

        private static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }

        protected void Edit_Detail_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList_Detail, panelGrid_Detail, panelCommand_Detail);
            cmdFac.SetPanelList(panelDateReqPick, "Edit");
            cmdFac.SetPanelList(panelDateReq, "Edit");
            cmdFac.SetPanelList(panelDuration, "Edit");
            LoadValidateDetail();
        }

        protected void EditSave_Detail_Click(object sender, EventArgs e)
        {
            try
            {
                BidderInfo infoBidder = new BidderInfo();
                MasterContactInfo infoMasContact = new MasterContactInfo();
                SysVatInfo infoVat = new SysVatInfo();
                SysDurationTypeInfo infoDurationType = new SysDurationTypeInfo();
                RecordInfo infoRecord = new RecordInfo();

                infoBidder.Seq = GetSeq();
                string[] TmpValue = cbSeller.SelectedValue.Split(':');
                infoMasContact.Seq = Convert.ToInt32(TmpValue[0]);
                infoVat.Seq = Convert.ToInt32(cbVatType.SelectedValue.ToString());
                infoBidder.VatPercent = Convert.ToDouble(txtVatPercent.Text);
                infoBidder.Date = Convert.ToDateTime(txtDate.TextWithLiterals);
                if (rdbDuration.Checked)
                {
                    if (txtDurationReq.Text.Length > 0)
                    {
                        infoBidder.DueDay = Convert.ToInt32(txtDurationReq.Text);
                        infoDurationType.Seq = Convert.ToInt32(cbDurationType.SelectedValue.ToString());
                    }
                }
                else if (rdbDate.Checked)
                {
                    if (txtDateReq.Text.Length > 0)
                    {
                        infoBidder.DueDate = Convert.ToDateTime(txtDateReq.TextWithLiterals);
                    }
                }

                infoRecord.Updated_by = 1;
                infoRecord.Updated_when = DateTime.Now;

                infoBidder.InfoMasContact = infoMasContact;
                infoBidder.InfoVat = infoVat;
                infoBidder.InfoDurationType = infoDurationType;
                infoBidder.InfoRecord = infoRecord;

                bllBidder.Update(infoBidder);
                GetKeyValue();
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
            }
        }

        protected void Cancel_Detail_Click(object sender, EventArgs e)
        {
            GetKeyValue();
        }

        private void LoadValidateDetail()
        {
            RequiredFieldValidator valSeller = new RequiredFieldValidator();
            valSeller.ID = "ValcbSeller";
            valSeller.ControlToValidate = "cbSeller";
            valSeller.SetFocusOnError = true;
            valSeller.Display = ValidatorDisplay.Dynamic;
            valSeller.ErrorMessage = "* กรุณาระบุผู้ขาย/รับจ้าง *";
            panelValcbSeller.Controls.Add(valSeller);
            RequiredFieldValidator valVatType = new RequiredFieldValidator();
            valVatType.ID = "ValcbVatType";
            valVatType.ControlToValidate = "cbVatType";
            valVatType.SetFocusOnError = true;
            valVatType.Display = ValidatorDisplay.Dynamic;
            valVatType.ErrorMessage = "* กรุณาระบุฐานภาษี *";
            panelValcbVatType.Controls.Add(valVatType);
            RequiredFieldValidator valVatPercent = new RequiredFieldValidator();
            valVatPercent.ID = "ValtxtVatPercent";
            valVatPercent.ControlToValidate = "txtVatPercent";
            valVatPercent.SetFocusOnError = true;
            valVatPercent.Display = ValidatorDisplay.Dynamic;
            valVatPercent.ErrorMessage = "* กรุณาระบุอัตราภาษี *";
            panelValtxtVatPercent.Controls.Add(valVatPercent);
            RequiredFieldValidator valDate = new RequiredFieldValidator();
            valDate.ID = "ValtxtDate";
            valDate.ControlToValidate = "txtDate";
            valDate.SetFocusOnError = true;
            valDate.Display = ValidatorDisplay.Dynamic;
            valDate.ErrorMessage = "* กรุณาระบุวันที่เสนอราคา *";
            panelValtxtDate.Controls.Add(valDate);
            CustomValidator valCustomDate = new CustomValidator();
            valCustomDate.ID = "ValCustomDate";
            valCustomDate.ControlToValidate = "txtDate";
            valCustomDate.SetFocusOnError = true;
            valCustomDate.Display = ValidatorDisplay.Dynamic;
            valCustomDate.ErrorMessage = "* กรุณาระบุวันที่เสนอราคาให้ถูกต้อง *";
            valCustomDate.ClientValidationFunction = "validateDate";
            panelValtxtDate.Controls.Add(valCustomDate);
            CustomValidator valCustomDateReq = new CustomValidator();
            valCustomDateReq.ID = "ValCustomDateReq";
            valCustomDateReq.ControlToValidate = "txtDateReq";
            valCustomDateReq.SetFocusOnError = true;
            valCustomDateReq.Display = ValidatorDisplay.Dynamic;
            valCustomDateReq.ErrorMessage = "* กรุณาระบุวันที่ส่งมอบให้ถูกต้อง *";
            valCustomDateReq.ClientValidationFunction = "validateDate";
            panelValReqDate.Controls.Add(valCustomDateReq);
            CustomValidator valCustom = new CustomValidator();
            valCustom.ID = "ValCustom";
            valCustom.SetFocusOnError = true;
            valCustom.Display = ValidatorDisplay.Dynamic;
            valCustom.ErrorMessage = "* กรุณาระบุระยะเวลาส่งมอบ *";
            valCustom.ClientValidationFunction = "validateDateReq";
            panelValReqDate.Controls.Add(valCustom);
        }

        # endregion;

        #region Tab รายการเสนอราคา

        protected void LoadGridItem()
        {
            IList<BidderQuotationInfo> infoListBidderQuotation = bllBidderQuo.GetListBidderQuotation(GetSeq());
            Grid_Item.DataSource = infoListBidderQuotation;
            Grid_Item.DataBind();
            cmdFac.GridCommand(panelList_Item, panelGrid_Item, panelCommand_Item);
        }

        protected void AddNew_Item_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList_Item, panelGrid_Item, panelCommand_Item);
            SetItemLabelVisible(true);
            LoadValidateItem();
        }

        private void LoadValidateItem()
        {
            RequiredFieldValidator ValcbItem = new RequiredFieldValidator();
            ValcbItem.ID = "ValcbItem";
            ValcbItem.ControlToValidate = "cbItem";
            ValcbItem.SetFocusOnError = true;
            ValcbItem.Display = ValidatorDisplay.Dynamic;
            ValcbItem.ErrorMessage = "* กรุณาระบุรายการพัสดุ *";
            panelValcbItem.Controls.Add(ValcbItem);

            RequiredFieldValidator ValtxtItemQty = new RequiredFieldValidator();
            ValtxtItemQty.ID = "ValtxtItemQty";
            ValtxtItemQty.ControlToValidate = "txtItemQty";
            ValtxtItemQty.SetFocusOnError = true;
            ValtxtItemQty.Display = ValidatorDisplay.Dynamic;
            ValtxtItemQty.ErrorMessage = "* กรุณาระบุจำนวน *";
            panelValtxtItemQty.Controls.Add(ValtxtItemQty);

            RequiredFieldValidator ValtxtItemPrice = new RequiredFieldValidator();
            ValtxtItemPrice.ID = "ValtxtItemPrice";
            ValtxtItemPrice.ControlToValidate = "txtItemPrice";
            ValtxtItemPrice.SetFocusOnError = true;
            ValtxtItemPrice.Display = ValidatorDisplay.Dynamic;
            ValtxtItemPrice.ErrorMessage = "* กรุณาระบุราคาต่อหน่วย *";
            panelValtxtItemPrice.Controls.Add(ValtxtItemPrice);
        }

        protected void Edit_Item_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList_Item, panelGrid_Item, panelCommand_Item);
            SetItemLabelVisible(true);
            LoadValidateItem();
        }

        protected void Delete_Item_Click(object sender, EventArgs e)
        {
            IList<BidderQuotationInfo> infoList = new List<BidderQuotationInfo>();
            if (panelGrid_Item.Visible)
            {
                foreach (GridDataItem data in Grid_Item.MasterTableView.GetSelectedItems())
                {
                    BidderQuotationInfo info = new BidderQuotationInfo();
                    info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                    infoList.Add(info);
                }
            }
            else
            {
                BidderQuotationInfo info = new BidderQuotationInfo();
                info.Seq = Convert.ToInt32(hdItemSeq.Value);
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllBidderQuo.DeleteFromDB(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadGridItem();
        }

        protected void AddNewSave_Item_Click(object sender, EventArgs e)
        {
            BidderQuotationInfo infoBidderQuotation = new BidderQuotationInfo();
            BidderInfo infoBidder = new BidderInfo();
            PurchaseRequestItemInfo infoPrItem = new PurchaseRequestItemInfo();
            ResourceMasterItemInfo infoItem = new ResourceMasterItemInfo();
            MasterUnitInfo infoUnit = new MasterUnitInfo();
            RecordInfo infoRecord = new RecordInfo();

            string[] TmpValue = cbItem.SelectedValue.Split(':');
            infoPrItem.Seq = Convert.ToInt32(TmpValue[0]);
            infoBidder.Seq = GetSeq();
            infoBidderQuotation.Descr = txtItemDescr.Text;
            infoBidderQuotation.Qty = Convert.ToInt32(txtItemQty.Text);
            infoBidderQuotation.Price = Convert.ToDouble(txtItemPrice.Text);
            infoBidderQuotation.ExcludeVatAmount = Convert.ToDouble(lblExcludeAmount.Text.Trim());
            infoBidderQuotation.VatAmount = Convert.ToDouble(lblVatAmount.Text.Trim());
            infoBidderQuotation.DiscountPercent = (txtDiscountPercent.Text == "") ? null : (Nullable<double>)Convert.ToDouble(txtDiscountPercent.Text);
            infoBidderQuotation.ExtraDiscount = (txtExtraDiscount.Text == "") ? null : (Nullable<double>)Convert.ToDouble(txtExtraDiscount.Text);
            infoBidderQuotation.NetAmount = Convert.ToDouble(lblTotalAmount.Text.Trim());
            infoBidderQuotation.Remarks = txtRemark.Text;
            infoRecord.Created_by = cn.UserID;
            infoRecord.Created_when = DateTime.Now;

            infoItem.InfoUnit = infoUnit;
            infoPrItem.InfoItem = infoItem;
            infoBidderQuotation.InfoPrItem = infoPrItem;
            infoBidderQuotation.InfoBidder = infoBidder;
            infoBidderQuotation.InfoRecord = infoRecord;

            try
            {
                bllBidderQuo.Insert(infoBidderQuotation);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }

            LoadGridItem();
        }

        protected void EditSave_Item_Click(object sender, EventArgs e)
        {
            BidderQuotationInfo infoBidderQuotation = new BidderQuotationInfo();
            BidderInfo infoBidder = new BidderInfo();
            PurchaseRequestItemInfo infoPrItem = new PurchaseRequestItemInfo();
            ResourceMasterItemInfo infoItem = new ResourceMasterItemInfo();
            RecordInfo infoRecord = new RecordInfo();

            if (cbItem.SelectedValue.Length > 0)
            {
                string[] TmpValue = cbItem.SelectedValue.Split(':');
                infoPrItem.Seq = Convert.ToInt32(TmpValue[0]);
            }
            infoBidder.Seq = GetSeq();
            infoBidderQuotation.Seq = Convert.ToInt32(hdItemSeq.Value);
            infoBidderQuotation.Descr = txtItemDescr.Text;
            infoBidderQuotation.Qty = Convert.ToInt32(txtItemQty.Text);
            infoBidderQuotation.Price = Convert.ToDouble(txtItemPrice.Text);
            infoBidderQuotation.ExcludeVatAmount = Convert.ToDouble(lblExcludeAmount.Text.Trim());
            infoBidderQuotation.VatAmount = Convert.ToDouble(lblVatAmount.Text.Trim());
            infoBidderQuotation.DiscountPercent = (txtDiscountPercent.Text == "") ? null : (Nullable<double>)Convert.ToDouble(txtDiscountPercent.Text);
            infoBidderQuotation.ExtraDiscount = (txtExtraDiscount.Text == "") ? null : (Nullable<double>)Convert.ToDouble(txtExtraDiscount.Text);
            infoBidderQuotation.NetAmount = Convert.ToDouble(lblTotalAmount.Text.Trim());
            infoBidderQuotation.Remarks = txtRemark.Text;
            infoRecord.Updated_by = Convert.ToInt32(Session["EmpSeq"].ToString());
            infoRecord.Updated_when = DateTime.Now;

            infoPrItem.InfoItem = infoItem;
            infoBidderQuotation.InfoPrItem = infoPrItem;
            infoBidderQuotation.InfoBidder = infoBidder;
            infoBidderQuotation.InfoRecord = infoRecord;

            try
            {
                bllBidderQuo.Update(infoBidderQuotation);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }

            GetQuotationValue(hdItemSeq.Value);
        }

        protected void Cancel_Item_Click(object sender, EventArgs e)
        {
            LoadGridItem();
        }

        protected void ShowGrid_Item_Click(object sender, EventArgs e)
        {
            LoadGridItem();
        }

        protected void cbItem_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            int seq = GetPrSeq();
            IList<PurchaseRequestItemInfo> infoList = bllPrItem.GetPurchaseRequestItem(e.Text, seq);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cbItem.Items.Add(new RadComboBoxItem(infoList[i].InfoItem.Name, infoList[i].Seq.ToString() + ":" + infoList[i].InfoItem.Name + ":" + infoList[i].InfoItem.InfoUnit.Name + ":" + infoList[i].Qty + ":" + infoList[i].Price));
                TableRow tr = new TableRow();
                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].InfoItem.Name;
                tdName.Width = Unit.Pixel(100);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);

                TableCell tdDescr = new TableCell();
                Label lblDescr = new Label();
                lblDescr.Text = infoList[i].Descr;
                tdDescr.Width = Unit.Pixel(100);
                tdDescr.Controls.Add(lblDescr);
                tr.Cells.Add(tdDescr);

                TableCell tdQty = new TableCell();
                Label lblQty = new Label();
                lblQty.Text = Convert.ToInt32(infoList[i].Qty).ToString("#,##0");
                tdQty.Width = Unit.Pixel(50);
                tdQty.HorizontalAlign = HorizontalAlign.Center;
                tdQty.Controls.Add(lblQty);
                tr.Cells.Add(tdQty);

                TableCell tdUnitName = new TableCell();
                Label lblUnitName = new Label();
                lblUnitName.Text = infoList[i].InfoItem.InfoUnit.Name;
                tdUnitName.Width = Unit.Pixel(50);
                tdUnitName.Controls.Add(lblUnitName);
                tr.Cells.Add(tdUnitName);

                TableCell tdPrice = new TableCell();
                Label lblPrice = new Label();
                lblPrice.Text = Convert.ToDouble(infoList[i].Price).ToString("#,##0.00");
                tdPrice.Width = Unit.Pixel(100);
                tdPrice.HorizontalAlign = HorizontalAlign.Center;
                tdPrice.Controls.Add(lblPrice);
                tr.Cells.Add(tdPrice);

                ((Table)cbItem.Items[j].FindControl("tableItem")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }

        protected void Grid_Item_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridItem();
        }

        protected void Grid_Item_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                double price = 0;
                GridDataItem dataBoundItem = e.Item as GridDataItem;

                if (((Label)(dataBoundItem["NetAmount"].FindControl("lblNetAmount"))).Text.Length > 0)
                {
                    price = double.Parse(((Label)(dataBoundItem["NetAmount"].FindControl("lblNetAmount"))).Text);
                }

                totalPrice += price;
            }
            else if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["InfoPrItem.ItemName"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>วงเงินทั้งหมด :</span> "));
                ((Label)footer["NetAmount"].FindControl("lblTotalPrice")).Text = totalPrice.ToString("###,###,##0.00");
            }
        }

        protected void GetQuotationValue(string seq)
        {
            BidderQuotationInfo info = new BidderQuotationInfo();
            info = bllBidderQuo.GetBidderQuotation(Convert.ToInt32(hdItemSeq.Value));
            lblItem.Text = info.InfoPrItem.ItemName;
            cbItem.Text = info.InfoPrItem.ItemName;
            txtItemDescr.Text = info.Descr;
            txtItemQty.Text = info.Qty.ToString();
            lblUnit.Text = info.InfoPrItem.InfoItem.InfoUnit.Name;
            txtItemPrice.Text = info.Price.ToString();
            lblVatTypeName.Text = info.InfoBidder.InfoVat.Name;
            lblExcludeAmount.Text = string.Format("{0:N2}", info.ExcludeVatAmount.ToString());
            lblVatPercent.Text = txtVatPercent.Value.ToString();
            lblVatAmount.Text = string.Format("{0:N2}", info.VatAmount.ToString());
            txtDiscountPercent.Text = info.DiscountPercent.ToString();
            txtExtraDiscount.Text = info.ExtraDiscount.ToString();
            lblDiscountPercentAmount.Text = Convert.ToString(info.NetAmount * ((txtDiscountPercent.Text.Length > 0 ? Convert.ToDouble(txtDiscountPercent.Text) : 0) / 100));
            lblTotalDiscountAmount.Text = Convert.ToString((txtExtraDiscount.Text.Length > 0 ? Convert.ToDouble(txtExtraDiscount.Text) : 0) + Convert.ToDouble(lblDiscountPercentAmount.Text));
            txtRemark.Text = info.Remarks;
            lblTotalAmount.Text = string.Format("{0:N2}", info.NetAmount.Value.ToString());
            hdExcludeVatAmount.Value = info.ExcludeVatAmount.ToString();
            hdVatAmount.Value = info.VatAmount.ToString();
            hdNetAmount.Value = info.NetAmount.Value.ToString();
            cmdFac.ViewCommand(panelList_Item, panelGrid_Item, panelCommand_Item);
            SetItemLabelVisible(true);
        }

        protected void SetItemLabelVisible(bool status)
        {
            lblUnit.Visible = status;
            lblVatTypeName.Visible = status;
            lblExcludeAmount.Visible = status;
            lblVatPercent.Visible = status;
            lblVatAmount.Visible = status;
            lblTotalAmount.Visible = status;
            lblDiscountPercentAmount.Visible = status;
            lblTotalDiscountAmount.Visible = status;
        }

        protected void RadManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            GetQuotationValue(e.Argument);
        }

        # endregion;

        #region Tab เอกสารการเสนอราคา

        protected void LoadGridFile()
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            Grid_File.DataSource = bllPprFile.GetDocument(seq, "icm_bidder_file", "icm_bidder_seq", "icm_bidder_file_seq");
            Grid_File.DataBind();

            cmdFac.GridCommand(panelList_File, panelGrid_File, panelCommand_File);
        }

        protected void Grid_File_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridFile();
        }

        protected void ShowGrid_File_Click(object sender, EventArgs e)
        {
            LoadGridFile();
        }

        protected void AddNew_File_Click(object sender, EventArgs e)
        {
            RequiredFieldValidator valFileName = new RequiredFieldValidator();
            valFileName.ID = "ValtxtFileName";
            valFileName.ControlToValidate = "txtFileName";
            valFileName.SetFocusOnError = true;
            valFileName.Display = ValidatorDisplay.Dynamic;
            valFileName.ErrorMessage = "* กรุณาระบุชื่อไฟล์ *";
            panelValtxtFileName.Controls.Add(valFileName);
            RequiredFieldValidator valAttachment = new RequiredFieldValidator();
            valAttachment.ID = "Valattachment";
            valAttachment.ControlToValidate = "attachment";
            valAttachment.SetFocusOnError = true;
            valAttachment.Display = ValidatorDisplay.Dynamic;
            valAttachment.ErrorMessage = "* กรุณาระบุที่อยู่ไฟล์ *";
            panelValattachment.Controls.Add(valAttachment);
            cmdFac.AddNewCommand(panelList_File, panelGrid_File, panelCommand_File);
        }

        protected void AddNewSave_File_Click(object sender, EventArgs e)
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            FileInfo infoFile = new FileInfo(hdSourceFile.Value);
            DocumentInfo info = new DocumentInfo();
            RecordInfo infoRecord = new RecordInfo();
            infoRecord.Created_by = Int32.Parse(Session["EmpSeq"].ToString());
            infoRecord.Created_when = DateTime.Now;
            info.File_info = infoFile;
            info.Name = txtFileName.Text;
            info.Dest_path = hdSourceFile.Value;
            info.InfoRecord = infoRecord;

            try
            {
                bllPprFile.InsertFileToDB(info, "ICM_BIDDER_FILE", "ICM_BIDDER_SEQ", seq);
                LoadGridFile();
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
        }

        protected void Delete_File_Click(object sender, EventArgs e)
        {
            IList<DocumentInfo> infoList = new List<DocumentInfo>();
            foreach (GridDataItem data in Grid_File.MasterTableView.GetSelectedItems())
            {
                DocumentInfo info = new DocumentInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                info.InfoRecord = infoRecord;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllPprFile.DeleteFileFromDB(infoList, "icm_bidder_file", "icm_bidder_file_seq");
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadGridFile();
        }

        # endregion;
    }
}
